﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Orchard;
using Orchard.DisplayManagement.Descriptors;
using Orchard.UI.Admin;
using Orchard.Widgets.Models;
using Orchard.Widgets.Services;

namespace NGM.Portlets {
    public class Shapes : IShapeTableProvider {
        private readonly IOrchardServices _orchardServices;
        private readonly IRuleManager _ruleManager;

        public Shapes(IOrchardServices orchardServices,
            IRuleManager ruleManager) {
            _orchardServices = orchardServices;
            _ruleManager = ruleManager;
        }

        public void Discover(ShapeTableBuilder builder) {
            builder.Describe("Zone")
                .Configure(descriptor => {
                    descriptor.Wrappers.Add("ZoneToolbarWrapper");
                })
                .OnCreated(created => {
                    var zone = created.Shape;
                    
                    var widgetService = _orchardServices.WorkContext.Resolve<IWidgetsService>();

                    var layers = widgetService.GetLayers().ToList();
                    zone.Layers = layers;

                    zone.Add(created.New.PlaceChildContent(Source: zone));
                })
                .OnDisplaying(displaying => {
                    var zone = displaying.Shape;

                    zone.Attributes.Add("data-zonename", zone.ZoneName);
                });

            builder.Describe("Widget")
                .Configure(descriptor => descriptor.Wrappers.Add("PortletsWrapper"))
                .OnDisplaying(displaying => {
                    var widget = displaying.Shape;
                    WidgetPart widgetPart = widget.ContentItem.WidgetPart;

                    var layerPart = widgetPart.LayerPart;

                    bool isAppliedToLayer = false;
                    try {
                        isAppliedToLayer = _ruleManager.Matches(layerPart.LayerRule);
                    }
                    catch (Exception e) {
                    }
                    
                    var widgetId = widgetPart.Id;

                    widget.Attributes.Add("data-widgetid", widgetId.ToString(CultureInfo.InvariantCulture));

                    //widget.Attributes.Add("layoutReordererId", string.Format("{0}|{1}|{2}", currentLayerId, widgetId));

                    if (!isAppliedToLayer)
                        widget.Classes.Add("widget-locked");
                });
        }
    }
}